import router, { asyncRoutes } from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from '@/utils/get-page-title.js'
const whiteList = ['/login', '/404'] // no redirect whitelist

router.beforeEach((to, from, next) => {
  document.title = getPageTitle(to.meta.title)
  next()
})

router.beforeEach(async(to, from, next) => {
  // 添加进度条
  NProgress.start()
  // 从vuex中取出token
  const token = store.state.user.token
  if (token) {
    // 到登录页
    if (to.path === '/login') {
      console.log('已经登录,转到主页')
      next('/')
      NProgress.done()
    } else {
      // 不去登录页

      if (!store.getters.userId) {
        const menus = await store.dispatch('user/getUserInfo')
        console.log('可以访问的页面', menus)
        // 根据用户权限，筛选出当前用户可以访问的页面
        const filterRoutes = asyncRoutes.filter(route => {
          const routeName = route.children[0].name
          return menus.includes(routeName)
        })
        // 把404页面放在最后一条
        // 404 page must be placed at the end !!!
        filterRoutes.push({ path: '*', redirect: '/404', hidden: true })

        // 动态添加方式
        router.addRoutes(filterRoutes)
        // 根据用户实际能访问几个页面来决定从整体路由设置中，过滤中出来几个，然后保存到vuex中
        store.commit('menu/setMenuList', filterRoutes)

        // 解决刷新出现的白屏bug
        next({
          ...to, // next({ ...to })的目的,是保证路由添加完了再进入页面 (可以理解为重进一次)
          replace: true // 重进一次, 不保留重复历史
        })
      } else {
        next()
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      console.log('没有登录，跳转到登录页')
      next('/login')
    }
  }
  // 结束进度条
  NProgress.done()
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
